<template>
  <div>
    <form action="/">
      <van-sticky :offset-top="0">
        <van-search
          v-model="value"
          placeholder="请输入搜索关键词"
          show-action
          shape="round"
          @search="onSearch"
          ref="search"
          @cancel="onCancel"
          autofocus
        >
          <!-- <div v-if="this.value" slot="action" @click="onSearch">搜索</div> -->
        </van-search>
      </van-sticky>
      <van-list v-model="loading" :finished="finished" :finished-text="finishedText" @load="onLoad">
        <van-grid :gutter="10" :column-num="3" square class="searchimg">
          <van-grid-item v-for="(item,i) of picList" :key="i" class="imgSize">
            <img class="lazy" @click="preview(i)" v-lazy="item.thumb" />
          </van-grid-item>
        </van-grid>
      </van-list>
    </form>
  </div>
</template>
<style>
.searchimg {
  margin-top: 3%;
}
</style>
<script>
export default {
  name: "search",
  data() {
    return {
      value: "",
      active: "",
      picList: [],
      loading: false,
      finished: true,
      l: 0,
      finishedText: ""
    };
  },
  methods: {
    preview(id) {
      this.previews(this.picList, "thumb", id);
    },
    async onSearch() {
      //搜索按钮
      this.picList = [];
      this.finishedText = "";

      this.l = 0;
      var val = encodeURI(encodeURI(this.value));
      let { data } = await this.axios.get(
        `?url=http%3a%2f%2fservice.avatar.adesk.com%2fv1%2favatar%2fsearch%3fkey%3d${val}%26adult%3d0%26first%3d1%26limit%3d30%26order%3d%26skip%3d0`
      );
      this.finished = false;
      if (!data.res.avatar.length) {
        this.finishedText = "没有搜到结果";
        this.finished = true;
      }
      this.picList = data.res.avatar;
    },
    onCancel() {
      this.$router.push("/");
    },
    async onLoad() {
      if (this.picList.length) {
        this.l += 30;
        var val = encodeURI(encodeURI(this.value));
        let { data } = await this.axios.get(
          `?url=http%3a%2f%2fservice.avatar.adesk.com%2fv1%2favatar%2fsearch%3fkey%3d${val}%26adult%3d0%26first%3d1%26limit%3d30%26order%3d%26skip%3d${this.l}`
        );
        this.finished = false;
        this.loading = false;
        if (!data.res.avatar.length) {
          this.finishedText = "已加载全部";
          this.finished = true;
        }
        this.picList = this.picList.concat(data.res.avatar);
      }
    }
  },
  mounted() {
    this.$refs.search.querySelector("input").focus();
  }
};
</script>
<style>
</style>